package com.wlxt.springcloud.book.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wlxt.springcloud.book.client.MemberDTO;
import com.wlxt.springcloud.book.client.MemberResultDTO;
import com.wlxt.springcloud.book.client.MemberServiceClient;
import com.wlxt.springcloud.book.constant.Constants;
import com.wlxt.springcloud.book.entity.Book;
import com.wlxt.springcloud.book.entity.Borrow;
import com.wlxt.springcloud.book.exception.BookNotFoundException;
import com.wlxt.springcloud.book.exception.MemberNotFoundException;
import com.wlxt.springcloud.book.exception.NotEnoughStockException;
import com.wlxt.springcloud.book.service.BookService;

@Service
public class BookServiceImpl implements BookService {

	@Autowired
	private MemberServiceClient memberServiceClient;
	
	@Override
	public List<Book> findAll() {
		List<Book> bookList = new ArrayList<>();
		bookList.addAll(Constants.BOOK_MAP.values());
		return bookList;
	}

	@Override
	public Book getInfo(String bid) {
		Book book = Constants.BOOK_MAP.get(bid);
		if(book == null) {
			throw new BookNotFoundException("BOOKID:" + bid + " not found");
		}
		return book;
	}

	@Override
	public void borrow(String bid, String mobile, Date takeDate, Date returnDate) {
		Book book = Constants.BOOK_MAP.get(bid);
		if(book == null) {
			throw new BookNotFoundException("BOOKID:" + bid + " not found");
		}
		if(book.getStock() == 0) {
			throw new NotEnoughStockException("Stock Not Enough");
		}
		MemberDTO memberDTO = null;
		MemberResultDTO mr = memberServiceClient.checkMobile(mobile);
		if(mr != null && "0".equals(mr.getCode()) && mr.getData() != null) {
			memberDTO = mr.getData();
		} else {
			throw new MemberNotFoundException("Member Not Found");
		}
		Borrow borrow = new Borrow();
		String brid = bid + "_" + memberDTO.getMid(); 
		borrow.setBrid(brid);
		borrow.setBid(bid);
		borrow.setMid(memberDTO.getMid());
		borrow.setCreateTime(new Date());
		borrow.setTaskData(takeDate);
		borrow.setReturnDate(returnDate);
		Constants.BORROW_MAP.put(brid, borrow);
		book.setStock(book.getStock() - 1);
		Constants.BOOK_MAP.put(book.getBid(), book);
	}
	
	@Override
	public List<Borrow> findAllBorrow() {
		
		List<Borrow> borrowList = new ArrayList<>();
		borrowList.addAll(Constants.BORROW_MAP.values());
		return borrowList;
	}
	
}
